import { useState, useEffect } from 'react'
import dayjs from 'dayjs'
import { parseWorkTimeData } from '../utils/dataParser'

export const useWorkTimeData = () => {
  // 工作时间数据状态
  const [workTimeData, setWorkTimeData] = useState([])
  // 筛选后的数据状态
  const [filteredData, setFilteredData] = useState([])
  // 加载状态
  const [loading, setLoading] = useState(false)

  // 从localStorage加载数据
  useEffect(() => {
    const savedData = localStorage.getItem('workTimeData')
    if (savedData) {
      try {
        const parsedData = JSON.parse(savedData)
        setWorkTimeData(parsedData)
        setFilteredData(parsedData)
      } catch (error) {
        console.error('加载数据失败:', error)
      }
    }
  }, [])

  // 保存数据到localStorage
  const saveData = (data) => {
    try {
      localStorage.setItem('workTimeData', JSON.stringify(data))
    } catch (error) {
      console.error('保存数据失败:', error)
    }
  }

  // 处理Excel导入
  const handleImportData = (data) => {
    setLoading(true)
    try {
      const parsedData = parseWorkTimeData(data)
      setWorkTimeData(parsedData)
      setFilteredData(parsedData)
      saveData(parsedData)
    } catch (error) {
      console.error('数据解析失败:', error)
    } finally {
      setLoading(false)
    }
  }

  // 处理数据筛选
  const handleFilterData = (filters) => {
    let filtered = [...workTimeData]

    // 按日期范围筛选
    if (filters.dateRange && filters.dateRange.length === 2) {
      const [startDate, endDate] = filters.dateRange
      filtered = filtered.filter((item) => {
        if (!item.date) return false

        const itemDate = dayjs(item.date).startOf('day')
        const start = dayjs(startDate).startOf('day')
        const end = dayjs(endDate).endOf('day')

        return (
          itemDate.isSameOrAfter(start, 'day') &&
          itemDate.isSameOrBefore(end, 'day')
        )
      })
    }

    // 按项目筛选
    if (filters.project && filters.project !== 'all') {
      filtered = filtered.filter((item) => item.project === filters.project)
    }

    // 按产品筛选
    if (filters.product && filters.product !== 'all') {
      filtered = filtered.filter((item) => item.product === filters.product)
    }

    // 按关键词搜索
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase()
      filtered = filtered.filter(
        (item) =>
          item.content.toLowerCase().includes(keyword) ||
          item.object.toLowerCase().includes(keyword)
      )
    }

    setFilteredData(filtered)
  }

  // 处理手动添加工时记录
  const handleAddWorkTime = (newRecord) => {
    const newData = [...workTimeData, newRecord]
    setWorkTimeData(newData)
    setFilteredData(newData)
    saveData(newData)
  }

  // 处理删除工时记录
  const handleDeleteWorkTime = (recordId) => {
    const newData = workTimeData.filter((item) => item.id !== recordId)
    setWorkTimeData(newData)
    setFilteredData(newData)
    saveData(newData)
  }

  // 处理编辑工时记录
  const handleEditWorkTime = (recordId, updatedRecord) => {
    const newData = workTimeData.map((item) =>
      item.id === recordId ? { ...item, ...updatedRecord } : item
    )
    setWorkTimeData(newData)
    setFilteredData(newData)
    saveData(newData)
  }

  // 清除所有数据
  const handleClearAllData = () => {
    setWorkTimeData([])
    setFilteredData([])
    localStorage.removeItem('workTimeData')
  }

  return {
    workTimeData,
    filteredData,
    loading,
    handleImportData,
    handleFilterData,
    handleAddWorkTime,
    handleDeleteWorkTime,
    handleEditWorkTime,
    handleClearAllData,
  }
} 